<template>
  <div class="app-container">
    <el-form :model="queryParams" :rules="rules" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="72px">
      <el-form-item label="物品名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入物品名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="申请类型" prop="applyType">
        <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item in applyTypeArray" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item in statusArray" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 时间范围 -->
      <el-form-item label="申请时间范围" prop="checkRangeTime" label-width="100px">
        <el-date-picker v-model="checkRangeTime" type="datetimerange" :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">筛选</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row v-show="checkOperate" :gutter="10" class="mb8">
      <span>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-check" size="mini" :disabled="multiple"
            @click="handleMultiple(true)" v-hasPermi="['warehousemanager:check:update']">审核通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-close" size="mini" :disabled="multiple"
            @click="handleMultiple(false)" v-hasPermi="['warehousemanager:check:update']">审核驳回</el-button>
        </el-col>
      </span>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" ref="applyTable"
      :default-sort="{ prop: 'checkId', order: 'ascending' }" @selection-change="handleSelectionChange">
      <el-table-column v-if="checkOperate" type="selection" :selectable="handleSelectDisable" width="55" align="center" />
      <el-table-column label="序号" align="center" width="55" type="index" :index.sync="indexMethod" />
      <el-table-column label="id" align="center" prop="checkId" width="55" v-if="false" />
      <el-table-column label="审批物品id" align="center" prop="itemId" v-if="false" />
      <el-table-column label="物品名称" align="center" prop="itemName" />
      <el-table-column label="申请数量" align="center" prop="itemNum" />
      <el-table-column label="仓库id" align="center" prop="deptId" v-if="false" />
      <el-table-column label="申请人" align="center" prop="checkApplicant" />
      <el-table-column label="来源" align="center" prop="deptName" />
      <el-table-column label="审批人" align="center" prop="checkAuditor" />
      <el-table-column label="申请时间" align="center" prop="checkApplicationTime" width="150" sortable>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="checkAuditingTime" width="150">
      </el-table-column>
      <el-table-column label="申请类型" align="center" prop="applyType">
        <template slot-scope="scope">
          <span v-if="scope.row.applyType == '1'">申请物品</span>
          <span v-if="scope.row.applyType == '0'">申请外库</span>
        </template>
      </el-table-column>
      <el-table-column label="申请外库操作" align="center" prop="applyOperateType" v-if="false" />
      <el-table-column label="操作" align="center" prop="status" width="200" class-name="small-padding fixed-width"
        fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleDetails(scope.row)"
            v-hasPermi="['warehousemanager:check:query']">详细信息</el-button>&nbsp;&nbsp;&nbsp;
          <span v-hasRole="['admin']">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['warehousemanager:check:delete']">删除</el-button>
          </span><!--管理员才能看到-->
          <span v-show="checkOperate">
            <span v-if="scope.row.status == '0'">| 已通过</span>
            <span v-if="scope.row.status == '1'">| 已驳回</span>
            <span v-if="scope.row.status == '2'">|
              <span v-hasRole="['department']">
                <el-button size="mini" type="text" icon="el-icon-check" @click="handleOperate(scope.row, true, false)"
                  v-hasPermi="['warehousemanager:check:update']">通过</el-button>
                <el-button size="mini" type="text" icon="el-icon-close" @click="handleOperate(scope.row, false, false)"
                  v-hasPermi="['warehousemanager:check:update']">驳回</el-button>
              </span>
              <span v-hasRole="['group']">未审核</span>
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="驳回提示" align="center" prop="content" v-if="false" />
      <el-table-column label="备注" align="center" prop="checkRemark" v-if="false" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 申请详细信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="55%" append-to-body>
      <div style="display:flex;text-align:center;justify-content: center;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="width: 70%;">
          <el-form-item label="审批物品id" prop="itemId" v-if="false" :offset="6">
            <el-input v-model="form.itemId" placeholder="请输入审批物品id" />
          </el-form-item>
          <el-form-item label="物品名称" prop="itemName" :span="12" :offset="6">
            <el-input v-model="form.itemName" placeholder="请输入物品名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="申请数量" prop="itemNum">
            <el-input v-model="form.itemNum" placeholder="请输入申请数量" :disabled="true" />
          </el-form-item>
          <el-form-item label="申请人" prop="checkApplicant">
            <el-input v-model="form.checkApplicant" placeholder="请输入申请人" :disabled="true" />
          </el-form-item>
          <el-form-item label="审批人" prop="checkAuditor" v-if="false">
            <el-input v-model="form.checkAuditor" placeholder="请输入审批人" />
          </el-form-item>
          <el-form-item label="申请时间" prop="checkApplicationTime">
            <el-input v-model="form.checkApplicationTime" placeholder="请选择申请时间" :disabled="true" />
          </el-form-item>
          <el-form-item label="审批时间" prop="checkAuditingTime" v-if="false">
            <el-date-picker clearable v-model="form.checkAuditingTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择审批时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="申请类型" prop="applyType">
            <el-input v-model="form.applyType" placeholder="申请类型" :disabled="true" />
          </el-form-item>
          <el-form-item v-if="form.applyType == '申请外库'" label="外库类型" prop="applyOperateType">
            <el-input v-model="form.applyOperateType" placeholder="申请类型" :disabled="true" />
          </el-form-item>
          <el-form-item label="备注" prop="content">
            <el-input v-model="form.content" :disabled.sync="determineDisabled" type="textarea" placeholder="无" />
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <span v-show="checkOperate">
          <el-button type="success" :disabled.sync="determineDisabled" @click="handleOperate(null, true, true)"
            v-hasPermi="['warehousemanager:check:update']">通过</el-button>
          <el-button type="danger" :disabled.sync="determineDisabled" @click="handleOperate(null, false, true)"
            v-hasPermi="['warehousemanager:check:update']">驳回</el-button>
        </span>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="applyDialogVisible" width="30%">
      <div>
        <div>确认执行此操作吗？</div>
        <br>
        <el-input v-model="contentSubmit" type="textarea" rows="4" placeholder="请输入信息" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="submitApplication">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listCheck, getCheck, delCheck, updateCheck, multipleOperateCheck } from "@/api/warehousemanager/check";

export default {
  name: "Check",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审核管理表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemName: null,
        itemNum: null,
        itemUnit: null,
        deptId: this.$store.getters.deptId,
        // checkApplicant: this.$store.getters.name,
        checkAuditor: null,
        checkApplicationTime: null,
        checkAuditingTime: null,
        applyType: null,
        applyOperateType: null,
        status: null,
        content: null,
        checkRemark: null
      },
      //设置是否显示“通过”、“驳回”、“未审核”等按钮---仅管理员权限下不显示
      checkOperate: true,
      //确认驳回对话框默认设置
      applyDialogVisible: false,
      //控制详细信息中的通过/驳回按钮是否可操作
      determineDisabled: false,
      //状态区分---是否为详细信息中的操作提交true；还是行中数据的操作提交false
      operateStatus: false,
      //对申请的审核结果，通过true or 拒绝false
      operateFlag: false,
      //提交数据，包括详细信息中的操作和表格行中的操作
      commitData: null,
      //行中确认数据时dialog中的content内容
      contentSubmit: "",
      applyTypeArray: [{
        value: '1',
        label: '物品申请'
      }, {
        value: '0',
        label: '外库申请'
      }],
      statusArray: [{
        value: '2',
        label: '未审核'
      }, {
        value: '0',
        label: '审核通过'
      }, {
        value: '1',
        label: '审核驳回'
      }],
      //日期时间选择器
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      checkRangeTime: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    if (this.$store.getters.name == 'admin') {
      this.checkOperate = false;
    } else {
      this.checkOperate = true;
    }

  },
  methods: {
    //自增序号
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询审核管理列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkId: null,
        itemId: null,
        itemName: null,
        itemNum: null,
        itemUnit: null,
        checkApplicant: null,
        checkAuditor: null,
        checkApplicationTime: null,
        checkAuditingTime: null,
        applyType: null,
        applyOperateType: null,
        status: null,
        content: null,
        checkRemark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getListByQuery();
    },
    /** 筛选查询审核管理列表 */
    getListByQuery() {
      this.loading = true;
      if (this.queryParams.itemName != null) {
        this.queryParams.itemName = this.queryParams.itemName.trim();
      }
      this.queryParams.checkApplicationTime = this.checkRangeTime[0];
      this.queryParams.checkAuditingTime = this.checkRangeTime[1];
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.checkRangeTime = '';
      this.resetForm("queryForm");
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.checkId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //设置禁止选择项（针对已经审核过的数据项）
    handleSelectDisable(row, index) {
      if (row.status != '2') {
        return false
      } else {
        return true
      }
    },
    /** 详细信息按钮操作 */
    handleDetails(row) {
      this.reset();
      const checkId = row.checkId || this.ids
      getCheck(checkId).then(response => {
        //记录变量作为通过/拒绝时的数据记录
        this.commitData = response.data;
        this.form = response.data;
        if (response.data.itemId == null) {
          this.form.itemName = response.data.checkRemark;
        }
        //转换显示格式，合理化显示
        this.form.applyType = (this.form.applyType == '0' ? '申请外库' : '申请物品');
        this.form.applyOperateType = (this.form.applyOperateType == '0' ? '报修' :
          (this.form.applyOperateType == '1' ? '报废' :
            (this.form.applyOperateType == '2' ? '回收' : '')));
        //判断是否可操作通过/驳回按钮；仅有未审核状态下可操作
        if (response.data.status != '2') {
          this.determineDisabled = true;
        } else {
          this.determineDisabled = false;
        }
        //只有车间负责人可编辑详细信息中的备注项，工区负责人和超级管理员不能输入此项
        if(!this.$store.getters.roles.includes('department')){
          this.determineDisabled = true;
        }
        this.open = true;
        this.title = "申请详细信息";

      });
    },

    // 单项审核操作方法
    //row为行数据信息,flag为申请时选择通过true或驳回false，operateStatus为详细信息中的审核按钮true或行中的审核按钮false
    handleOperate(row, flag, operateStatus) {
      this.operateFlag = flag;
      this.operateStatus = operateStatus;

      if (operateStatus == true) { //点击详细信息中的通过/拒绝操作
        this.submitApplication();
      } else {
        this.commitData = row;
        this.applyDialogVisible = true;
      }
    },
    //多选提交
    handleMultiple(flag) {
      let selectData = this.$refs.applyTable.selection
      //遍历 更新状态
      for (const item in selectData) {
        if (flag == true) {
          selectData[item].status = '0';
        } else {
          selectData[item].status = '1';
        }
        selectData[item].deptId = this.$store.getters.deptId;
        selectData[item].checkAuditor = this.$store.getters.name;
      }
      this.$modal.confirm('是否确认此次操作？').then(function () {
        return multipleOperateCheck(selectData);
      }).then(response => {
        this.getList();
        this.$modal.msgSuccess(response.msg);
      }).catch((action) => {
        //取消按钮及右上角的关闭按钮回调
        //在catch方法的回调参数中传递action，判断action的值为 cancel 还是 close，如果是close，就代表操作为点击右上角按钮，为 cancel，就是点击的取消按钮
        for (const item in selectData) {
          selectData[item].status = '2';
        }
        return;
      });
    },
    //申请操作处理提交---
    //提交数据到后端
    submitApplication() {
      //flag=true 通过申请
      if (this.operateFlag == true) {
        this.commitData.status = '0';
      } else {
        this.commitData.status = '1';
      }
      //this.operateStatus==false 申请操作处理提交---行中的操作确认按钮
      if (this.operateStatus == false) {
        this.commitData.content = this.contentSubmit;
      } else {
        this.commitData.applyType = (this.form.applyType == '申请外库' ? '0' : '1');
        this.commitData.applyOperateType = (this.form.applyOperateType == '报修' ? '0' :
          (this.form.applyOperateType == '报废' ? '1' :
            (this.form.applyOperateType == '回收' ? '2' : '')));
        this.commitData.content = this.form.content;
      }
      this.commitData.checkAuditor = this.$store.getters.name;//审核人
      this.commitData.deptId = this.$store.getters.deptId;//仓库id
      updateCheck(this.commitData).then(response => {
        if (response.msg == '0') {
          this.$modal.msgSuccess("操作成功！");
        } else {
          this.$modal.msgError(response.data);
        }
        //operateStatus==false
        if (this.operateStatus == false) {
          this.applyDialogVisible = false;
          //提交之后清空对话框内容
          this.contentSubmit = "";
        } else {
          this.open = false;
        }
        this.getList();
      });
    },
    //取消提交，状态回退
    cancelSubmit() {
      this.applyDialogVisible = false;
      //清空对话框内容
      this.contentSubmit = "";
      this.$refs.applyTable.clearSelection();
      this.commitData.status = '2';
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const checkIds = row.checkId || this.ids;
      this.$modal.confirm('是否确认删除审核管理编号为"' + checkIds + '"的数据项？').then(function () {
        return delCheck(checkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehousemanager/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
